package utils

import (
	"net"
	"net/http"
	"strings"
)

// IpAddr 获取客户端的IP地址
func IpAddr() string {
	if address, err := net.InterfaceAddrs(); err == nil {
		for _, addr := range address {
			if ipAddr, ok := addr.(*net.IPNet); ok && !ipAddr.IP.IsLoopback() {
				if ipAddr.IP.To4() != nil {
					return ipAddr.IP.String()
				}
			}
		}
	}
	return ""
}

// GetClientIP 根据HTTP请求头信息获取客户端真实IP地址
func GetClientIP(req *http.Request) string {
	xForwardedFor := req.Header.Get("X-Forwarded-For")
	clientIP := ""
	if xForwardedFor != "" {
		clientIP = xForwardedFor
	} else if ip := req.Header.Get("X-Real-Ip"); ip != "" {
		clientIP = ip
	} else {
		hostPort := strings.Split(req.RemoteAddr, ":")
		if len(hostPort) > 0 {
			clientIP = hostPort[0]
		}
	}
	return clientIP
}

// MacAddr 获取客户端的MAC地址
func MacAddr() string {
	if interfaces, err := net.Interfaces(); err == nil {
		for _, inter := range interfaces {
			return string(inter.HardwareAddr)
		}
	}
	return ""
}
